package com.hgd.security.evp.biz.rabbitmq;

import com.hgd.security.evp.biz.biz.EvpUserBiz;
import com.hgd.security.evp.biz.entity.EvpUser;
import com.rabbitmq.client.Channel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * @author By 尚
 * @date 2019/5/21 9:59
 */
@Component
public class HGDRabbitMQReceive {

    @Autowired
    private EvpUserBiz evpUserBiz;

    @RabbitListener(
        bindings = @QueueBinding(
            value = @Queue(
                value = "${hgd.rabbitmq.user.queue}",
                durable = "${hgd.rabbitmq.user.durable}"
            ),
            exchange = @Exchange(
                value = "${hgd.rabbitmq.user.exchange}",
                type = "${hgd.rabbitmq.user.exchangeType}",
                ignoreDeclarationExceptions = "${hgd.rabbitmq.user.ignoreDeclarationExceptions}"
            ),
            key = "userRouting.*"
        )
    )
    @RabbitHandler
    public void onUserMessage(@Payload EvpUser user, @Headers Map<String, Object> headers, Channel channel) {
//        if(StringUtils.equals(String.valueOf(headers.get("giveWrong")),"true")){
//            System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
//            throw new IOException("An IOException");
//        }

        try {
            evpUserBiz.insertSelectiveBindCrt(user);
            System.out.println(Thread.currentThread().getName()+user.getUserName()+"添加成功");
            Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
